/*
 * $Id: mutex.c,v 1.4 2005-12-15 07:19:12 bacon Exp $
 */

#include <xp/bas/thr.h>
#include <xp/bas/mtx.h>
#include <xp/bas/time.h>
#include <xp/bas/stdio.h>

#ifdef __linux
#include <mcheck.h>
#endif

xp_mtx_t mutex;

int dummy (xp_thr_t* thr)
{
	int i;

	xp_mtx_lock (&mutex);
	for (i = 0; i < 5; i++) {
		xp_printf (XP_TEXT("dummy1. %i\n"), i);
		xp_sleep (1000);
	}
	xp_mtx_unlock (&mutex);

	return 0;
}

int dummy2 (xp_thr_t* thr)
{
	int i;

	xp_mtx_lock (&mutex);
	for (i = 0; i < 5; i++) {
		xp_printf (XP_TEXT("dummy2. %i\n"), i);
		xp_sleep (1000);
	}
	xp_mtx_unlock (&mutex);

	return 0;
}

int dummy3 (xp_thr_t* thr)
{
	int i;

	xp_mtx_lock (&mutex);
	for (i = 0; i < 5; i++) {
		xp_printf (XP_TEXT("dummy3. %i\n"), i);
		xp_sleep (1000);
	}
	xp_mtx_unlock (&mutex);

	return 0;
}

int xp_main ()
{
	xp_thr_t thr1, thr2, thr3;

#ifdef __linux
	mtrace ();
#endif

	if (xp_mtx_open (&mutex) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open mutex\n"));
		return -1;
	}

	if (xp_thr_open (&thr1, dummy, 0) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open thread\n"));
		return -1;
	}
	if (xp_thr_open (&thr2, dummy2, 0) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open thread\n"));
		return -1;
	}
	if (xp_thr_open (&thr3, dummy3, 0) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open thread\n"));
		return -1;
	}

	if (xp_thr_start (&thr1, 0) == -1) {
		xp_printf (XP_TEXT("cannot start thread\n"));
		return -1;
	}
	if (xp_thr_start (&thr2, 0) == -1) {
		xp_printf (XP_TEXT("cannot start thread\n"));
		return -1;
	}
	if (xp_thr_start (&thr3, 0) == -1) {
		xp_printf (XP_TEXT("cannot start thread\n"));
		return -1;
	}

	xp_thr_join (&thr1);
	xp_thr_join (&thr2);
	xp_thr_join (&thr3);
	xp_thr_close (&thr1);
	xp_thr_close (&thr2);
	xp_thr_close (&thr3);

	xp_mtx_close (&mutex);

#ifdef __linux
	muntrace ();
#endif

	return 0;
}
